# -*- coding:utf-8 -*-

'''
    Read data:
    1. Measurement data including time and meta data
    2. propagation progress-related data
'''
from  builtins import range
import os.path
import numpy as np
import logging
import json
from aod.satProp import DEFAULTINITPSE

DEFAULTPROGRESSFILE  = './data/progressData/defaultprogress.data'

def readProgressData(filename):
    filep =  open(filename,'r')
    data = json.load(filep)
    filep.close()
    return data

def dumpProgressData(filename,sats):
    filep =  open(filename,'w')
    satInitState =  []
    satTimeDrift  =  [] 
    frontTime    =  []   # the most recent link record
    frontIndex   =  []
    satCurrentTime  = []
    satRecordFileIndex = []
    satnum = 0
    jsonData ={}
    for sat in sats:
        satnum = satnum+1
        satRecordFileIndex .append(1)

        satCurrentTime.append(sat.curtruetime)
        satInitState .append({'mean':sat.kine.mean.tolist(),'cov':sat.kine.cov.tolist()} )
        satTimeDrift.append({'mean':[0],'cov':[[30]]})
        frontTime.append(sat.curtruetime)
        frontIndex.append(0)
    jsonData['satCurrentTime'] = satCurrentTime
    jsonData['satInitState'] = satInitState
    jsonData['satTimeDrift'] = satTimeDrift
    jsonData['frontTime'] = frontTime
    jsonData['frontIndex'] = frontIndex
    jsonData['satRecordFileIndex']=satRecordFileIndex

    json.dump(jsonData,filep)
    filep.close()


class dataRead(object):
    '''
        DataRead method
    '''
    def __init__(self,datafolder):
        self.datafolder = datafolder
        self.fileHandlers = []
        self.initTime   =  508*604800 + 388803.0   # TODO modifiable
    
    def readFile(self,satNums= list(range(1,25))):
        if (isinstance(satNums,list)==False):
            satNums = [satNums]
        data = []
        for sat in satNums:
            logging.debug('read sat%d file' %sat)
            satstr    =  '%02d'% sat
            satfilenameCache = self.datafolder+ '/H82-Sat'+ satstr+'-01.npy'
            if(os.path.isfile(satfilenameCache)):
                data.append(np.load(satfilenameCache))
            else:
                logging.debug('read file and generate data cache of sat%d' %sat)
                satfilename = '/H82-Sat'+ satstr+'-01.txt'
                filehandler= open(self.datafolder+satfilename,'r')
                filedata   =  filehandler.read().splitlines()
                filehandler.close()
                fdata     = []
                for aline in filedata:
                    tmpstrlist = aline.split()
                    for index in range(0,7):
                        if(index in [2,5,6]):
                            tmpstrlist[index]  = float(tmpstrlist[index])   
                        else:
                            tmpstrlist[index]  = int(tmpstrlist[index])
                    fdata.append(tmpstrlist)
                fdata  = np.array(fdata,dtype=float)
                np.save(satfilenameCache,fdata)
                data.append(fdata)
        self.data = data
        return data
    def readInitialState(self,stateFile='Init_Orbit.txt'):
        '''
            initialData structure: [sat1, sat2,...]
            sat1 structure [satnum, x]
        '''
        filehandler= open(self.datafolder+'/'+stateFile,'r')
        filedata   =  filehandler.read().splitlines()
        filehandler.close()
        fdata     = []
        for aline in filedata:
            tmpstrlist = aline.split()
            for index in range(0,len(tmpstrlist)):
                tmpstrlist[index]  = float(tmpstrlist[index])   
            fdata.append(tmpstrlist)
        self.initialData = fdata
        return fdata
    def fetchdata(self):
        self.readFile()
        self.readInitialState()
    def readtrueResult(self,datafiledfolder = './data/ECI/'):
        data = []
        for sat in range(1,25):
            satstr    =  '%02d'% sat
            satfilenameCache = datafiledfolder+ 'Sat'+ satstr+'.npy'
            data.append(np.load(satfilenameCache))
        return data
        
    def readProgressData(self,filename = DEFAULTPROGRESSFILE):
        return readProgressData(filename)

    def storeProgressData(self,data,filename = DEFAULTPROGRESSFILE ):
        filep = open(filename,'w')
        json.dump(data,filep)
        filep.close()
        return 0
if __name__ == '__main__':
    # logging.basicConfig(level=logging.DEBUG,format='%(message)s')
    # dataread  =  dataRead()
    # data = dataread.readFile()
    # # print data
    # initialData = dataread.readInitialState()
    data = dataRead()
    data.fetchdata()
    jsonData = {}
    # variables should be stored
    # initialTime
    # satInitState
    # satTimeDrift
    # frontIndex
    # frontTime
    truedatafolder = './data/ECI/'
    print data.initTime
    satInitState =  []
    satTimeDrift  =  [] 
    frontTime    =  []   # the most recent link record
    frontIndex   =  []
    satCurrentTime  = []
    satRecordFileIndex = []
    for satnum in range(0,24):
        satRecordFileIndex .append(1)
        satstr    =  '%02d'% (satnum+1)
        print satstr
        satfilenameCache = truedatafolder + 'Sat'+ satstr+'.npy'
        # fdata     = np.load(satfilenameCache)

        satCurrentTime.append(data.initTime)
        # satCurrentTime.append(fdata[0,0])
        satInitState .append({'mean':data.initialData[satnum][1:7],'cov':DEFAULTINITPSE.tolist()} )
        # satInitState .append({'mean': fdata[0,1:7].tolist(),'cov':np.zeros((6,6)).tolist()} )
        satTimeDrift.append({'mean':[0],'cov':[[30]]})
        frontTime.append(data.data[satnum][0][1]*604800+data.data[satnum][0][2])
        frontIndex.append(0)
    jsonData['satCurrentTime'] = satCurrentTime
    jsonData['satInitState'] = satInitState
    jsonData['satTimeDrift'] = satTimeDrift
    jsonData['frontTime'] = frontTime
    jsonData['frontIndex'] = frontIndex
    jsonData['satRecordFileIndex']=satRecordFileIndex
    data.storeProgressData(jsonData)